//
//  UIApplication+Current.swift
//  PDFSign
//
//  Created by 李永彬 on 2025/9/18.
//

import UIKit

extension UIApplication {
    var currentWindow: UIWindow? {
        UIApplication.shared.connectedScenes
            .filter { $0.activationState == .foregroundActive }
            .first(where: { $0 is UIWindowScene })
            .flatMap({ $0 as? UIWindowScene })?.windows
            .first(where: \.isKeyWindow)
    }
}

extension UIApplication {
    /// 获取基于LYMainViewController架构的最上层显示控制器
    static func topViewController() -> UIViewController? {
        guard let rootViewController = self.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController else {
            return nil
        }
        
        // 确认根控制器是LYMainViewController
        guard let mainVC = rootViewController as? WJMainTabViewController else {
            return nil
        }
        
        // 从LYMainViewController开始查找
        return findTopViewController(startingFrom: mainVC)
    }
    
    private class func findTopViewController(startingFrom viewController: UIViewController) -> UIViewController {
        // 1. 首先检查是否有模态弹出的控制器
        if let presented = viewController.presentedViewController {
            return findTopViewController(startingFrom: presented)
        }
        
        // 2. 如果是导航控制器，返回可见的控制器
        if let nav = viewController as? UINavigationController {
            if let visibleVC = nav.visibleViewController {
                return findTopViewController(startingFrom: visibleVC)
            }
            return nav
        }
        
        // 3. 如果是标签栏控制器，返回选中的控制器
        if let tab = viewController as? UITabBarController {
            if let selected = tab.selectedViewController {
                return findTopViewController(startingFrom: selected)
            }
            return tab
        }
        
        // 4. 如果是LYMainViewController，检查它的child控制器
        if let mainVC = viewController as? WJMainTabViewController {
            for child in mainVC.children.reversed() {
                if child.isViewLoaded && child.view.window != nil {
                    return findTopViewController(startingFrom: child)
                }
            }
        }
        
        // 5. 默认返回当前控制器
        return viewController
    }
}

